#!/usr/bin/env python
#_*_ coding:utf-8 _*_
from django.shortcuts import render, render_to_response, HttpResponse, redirect
from forum import models
import json
from django.core import serializers
from datetime import date
import datetime
# Create your views here.
def login(request):
    if request.method=='POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            currentObj = models.Admin.objects.get(username=username,password=password)
        except Exception,e:
            currentObj=None    
        
        if currentObj:
            request.session['current_user_id']=currentObj.id
            return redirect('/index/')
        else:
            return render_to_response('login.html')
    return render_to_response('login.html')
    

def index(request):
    all_data = models.News.objects.all()
    return render_to_response('index.html',{'data':all_data})
def addFavor(request):
    ret = {'status':0,'data':'','msg':''}
    try:
        if request.method=='POST':
            id =request.POST.get("nid")
            newsObj = models.News.objects.get(id=id)
            temp=newsObj.favor_count+1
            newsObj.favor_count=temp
            newsObj.save()
            ret['status']=1
            ret['data']=temp
            #return HttpResponse(temp)
    except Exception, e:
        ret['status']=0
        ret['msg']=e.message
        print e
    return HttpResponse(json.dumps(ret))

def getReply(request):
    ret = {'status':0,'data':'','msg':''}
    try:
        if request.method=='POST':
            id =request.POST.get("nid")
            #newsObj = models.Reply.objects.filter(new)
            reply_list = models.Reply.objects.filter(news__id=id).values('id','content','create_date','user__username')
            reply_list=list(reply_list)
            #reply_list=serializers.serialize('json', reply_list)
            reply_list=json.dumps(reply_list,cls=CJsonEncoder)
            print reply_list
            print reply_list
            ret['status']=1
            #ret['data']=temp
            #return HttpResponse(temp)
    except Exception, e:
        ret['status']=0
        ret['msg']=e.message
        print e
    return HttpResponse(reply_list)
def submitReply(request):
    ret = {'status':0,'data':'','msg':''}
    try:
        if request.method=='POST':
            id =request.POST.get("nid")
            data =request.POST.get("data")
            newsObj=models.News.objects.get(id=id)
            obj = models.Reply.objects.create(content=data,
                                         user=models.Admin.objects.get(id=request.session['current_user_id']),
                                         news=newsObj)
            temp=newsObj.reply_count+1
            newsObj.reply_count=temp
            newsObj.save()
            
            
            #print id,data
            #newsObj = models.Reply.objects.filter(new)
            #===================================================================
            # reply_list = models.Reply.objects.filter(news__id=id).values('id','content','create_date','user__username')
            # reply_list=list(reply_list)
            # #reply_list=serializers.serialize('json', reply_list)
            # reply_list=json.dumps(reply_list,cls=CJsonEncoder)
            #===================================================================
            ret['status']=1
            ret['data']={'reply_count':temp,'content':obj.content,'user__username':obj.user.username,'create_date':obj.create_date.strftime('%Y-%m-%d %H:%M:%S')}
            #ret['data']=temp
            #return HttpResponse(temp)
    except Exception, e:
        ret['status']=0
        ret['msg']=e.message
        #print e
    return HttpResponse(json.dumps(ret))
def submitChatMsg(request):
    ret = {'status':0,'data':'','msg':''}
    try:
        if request.method=='POST':
            value =request.POST.get("data")
            userObj=models.Admin.objects.get(id=request.session['current_user_id'])
            chatObj = models.Chat.objects.create(content=value, user=userObj)
            
            
            
            #print id,data
            #newsObj = models.Reply.objects.filter(new)
            #===================================================================
            # reply_list = models.Reply.objects.filter(news__id=id).values('id','content','create_date','user__username')
            # reply_list=list(reply_list)
            # #reply_list=serializers.serialize('json', reply_list)
            # reply_list=json.dumps(reply_list,cls=CJsonEncoder)
            #===================================================================
            ret['status']=1
            ret['data']={'username':userObj.username,'create_date':chatObj.create_date.strftime('%Y-%m-%d %H:%M:%S')}
            #ret['data']=temp
            #return HttpResponse(temp)
    except Exception, e:
        ret['status']=0
        ret['msg']=e.message
        #print e
    return HttpResponse(json.dumps(ret))
def getChats(request):
    ret = {'status':0,'data':'','msg':''}
    try:
        if request.method=='POST':
            chatList = models.Chat.objects.all().order_by('-id')[0:10].values('id','content','user__username','create_date')
            chatList=list(chatList)
            #last_id=chatList[0]['id']
            #print last_id
            chatList=json.dumps(chatList,cls=CJsonEncoder)
            
            
    except Exception, e:
        ret['status']=0
        ret['msg']=e.message
        #print e
    return HttpResponse(chatList)
def getChats2(request):
    ret = {'status':0,'data':'','msg':''}
    try:
        if request.method=='POST':
            lastId=request.POST.get('lastId')
            chatList = models.Chat.objects.filter(id__gt=lastId).order_by('-id')[0:10].values('id','content','user__username','create_date')
            chatList = list(chatList)
            chatList=json.dumps(chatList,cls=CJsonEncoder)
    except Exception, e:
        ret['status']=0
        ret['msg']=e.message
        #print e
    return HttpResponse(chatList)

class CJsonEncoder(json.JSONEncoder):
    def default(self,obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)